package com.zzb.listener;

import com.zzb.dao.UserDao;
import com.zzb.entity.UserEntity;
import com.zzb.repostitory.UserRepository;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.messaging.handler.annotation.Headers;
import org.springframework.messaging.handler.annotation.Payload;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.Map;

@Slf4j
@Component
public class UserMQListener {
    private static final String ADD = "add";
    @Resource
    UserDao userDao;
    @Resource
    RedisTemplate<String, UserEntity> redisTemplate;
    @Autowired
    private UserRepository userRepository;

    @RabbitListener(queues = "zzb_user")//从哪些队列里取消息，可以写多个，写的是队列名。
//    @RabbitListener(queuesToDeclare = @Queue("zzb_user"))// 这个也可以，只是这个传的是Queue对象。
    public void userReceive(String message, @Payload String body, @Headers Map headers) {
        //对接收的消息进行处理
        String[] messages = message.split("-");
        ValueOperations<String, UserEntity> valueOperations = redisTemplate.opsForValue();
        //从redis中将数据取出
        UserEntity userEntity = valueOperations.get(messages[1]);
        if (messages[0].equals(ADD)) {
            //将数据添加到数据库
            userDao.add(userEntity);
            UserEntity byName = userDao.findByName(userEntity);
            //将数据放入es
            userRepository.save(byName);

        }
        log.info("payload:{}", body);
        log.info("headers:{}", headers);
        log.info("user收到消息，消息内容是: {}", message);
    }
}